package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.common.util.Utility;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.AreaService;
import co.gov.medellin.ssti.sub.model.service.ProgramaService;
import co.gov.medellin.ssti.sub.model.service.RepBeneficioOtorgadoService;
import co.gov.medellin.ssti.sub.model.service.ReportTotalBenBerService;
import co.gov.medellin.ssti.sub.model.service.SedeService;
import co.gov.medellin.ssti.sub.model.service.SubprogramaService;
import co.gov.medellin.ssti.sub.model.vo.AreaVO;
import co.gov.medellin.ssti.sub.model.vo.ProgramaVO;
import co.gov.medellin.ssti.sub.model.vo.RepDetBeneficiarioVO;
import co.gov.medellin.ssti.sub.model.vo.ReportTotalBenBerVO;
import co.gov.medellin.ssti.sub.model.vo.SedeVO;
import co.gov.medellin.ssti.sub.model.vo.SubprogramaVO;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;

public class ReportTotalBENBERAction extends Action {
	@Autowired
	AreaService areaServiceImpl;
	@Autowired
	ProgramaService programaServiceImpl;
	@Autowired
	RepBeneficioOtorgadoService repBeneficioOtorgadoServiceImpl;
	@Autowired
	ReportTotalBenBerService reportTotalBenBerServiceImpl;
	@Autowired
	SedeService sedeServiceImpl;
	@Autowired
	SubprogramaService subprogramaServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		Object codePrograma = (Object) request.getParameter("codePrograma");

		HttpSession session = request.getSession();
		UserVO user = (UserVO) session.getAttribute("userInfo");
		session.removeAttribute("msg");
		session.setAttribute("msg", "");
		Collection<AreaVO> areas = null;
		Collection<ProgramaVO> programas = null;
		Collection<SubprogramaVO> subprogramas = null;
		Collection<SedeVO> sedes = null;

		session.removeAttribute("Beneficios");
		String strarea = request.getParameter("codearea");

		try {
			sedes = sedeServiceImpl.loadAllSedes();
		} catch (DAOException e) {
			SUBException.logDebugError("", e);
		}
		if (sedes.size() > 0) {
			session.setAttribute("sedes", sedes);

			try {
				areas = areaServiceImpl
						.findAreasAuthorized(String.valueOf(user.getCode()),
								user.getUserGroupName());
			} catch (DAOException e) {
				SUBException.logDebugError("", e);
			}

			if (areas.size() > 0) {
				session.setAttribute("areas", areas);

				if ((Object) strarea != null && !strarea.equals("nulo")) {
					session.removeAttribute("programas");
					session.removeAttribute("subprogramas");

					try {
						ProgramaVO objProgramaVO = new ProgramaVO();
						objProgramaVO.setCodeArea(new Long(strarea));
						programas = (List<ProgramaVO>) programaServiceImpl
								.findProgramaByCriteria(objProgramaVO,
										user.getUserGroupName(),
										user.getCode(), user.getCodeArea());
					} catch (DAOException e) {
						SUBException.logDebugError("", e);
					}
					if (programas.size() > 0) {
						session.setAttribute("programas", programas);
					}

				} else {
					try {
						programas = repBeneficioOtorgadoServiceImpl
								.findProgramaByUserReport(user.getCode(),
										user.getUserGroupName(),
										user.getCodeArea());
					} catch (DAOException e) {
						SUBException.logDebugError("", e);
					}
					session.removeAttribute("msg");
					if (programas.size() > 0) {
						session.setAttribute("programas", programas);
					} else {
						session.setAttribute("msg",
								"No se encontraron programas vigentes a la fecha..");
					}
				}
				if (codePrograma != null) {

					String codpro = (String) codePrograma;
					if (!codpro.equals("nulo")) {
						try {
							String strCodeProg = (String) codePrograma;
							SubprogramaVO vo = new SubprogramaVO();
							vo.setCode(Long.valueOf(strCodeProg));
							subprogramas = subprogramaServiceImpl
									.findAllowedSubprograma(vo, user.getCode(),
											user.getUserGroupName(),
											user.getCodeArea());
							// subprogramas = repBeneficioOtorgadoServiceImpl
							// .findSubProgramaByUserReport(
							// user.getCode(),
							// user.getUserGroupName(),
							// strCodeProg, user.getCodeArea());
						} catch (DAOException e) {
							SUBException.logDebugError("", e);
						}
						session.removeAttribute("msg");
						if (subprogramas.size() > 0) {
							session.setAttribute("subprogramas", subprogramas);
						} else {
							session.setAttribute("msg",
									"No se encontraron subprogramas asociados a este programa que esten vigentes..");
						}
					} else {
						session.setAttribute("msg", "");
						session.removeAttribute("subprogramas");
					}
				}
			} else {
				session.setAttribute("msg", "No se encontraron areas..");
			}
		} else {
			session.setAttribute("msg",
					"No se encontraron sedes vigentes a la fecha..");
		}

		String accion = (request.getParameter("acciones") == null) ? ""
				: request.getParameter("acciones");
		Object codeSede = request.getParameter("code");
		Object codeSubprograma = request.getParameter("codeSubPrograma");
		String codeSede1 = (String) codeSede;
		String codeSubprograma1 = (String) codeSubprograma;
		String codePrograma1 = (String) codePrograma;

		boolean continuar = true;

		// fecha inicial
		String fechaini = (request.getParameter("fechaInicial") == null) ? ""
				: request.getParameter("fechaInicial");
		String fechafinal = (request.getParameter("fechaFinal") == null) ? ""
				: request.getParameter("fechaFinal");

		// validar fechas..
		if (!fechaini.equals("") && !fechafinal.equals("")) {
			if (!Utility.isDateValid(fechaini)) {
				request.setAttribute("errorfecha",
						"La fecha inicial es incorrecta");
				continuar = false;
			} else if (!Utility.isDateValid(fechafinal)) {
				request.setAttribute("errorfecha",
						"La fecha final es incorrecta");
				continuar = false;
			} else {
				Date fIni = new Date(fechaini);
				Date fFin = new Date(fechafinal);
				if (fIni.after(fFin)) {
					request.setAttribute("errorfecha",
							"La fecha inicial es mayor a la final");
					continuar = false;
				}
			}
		}

		if (continuar) {
			session.removeAttribute("beneficiosSede");
			if (accion.equals("BuscarTodo")) {
				Collection<ReportTotalBenBerVO> cobeneficio = null;
				try {

					RepDetBeneficiarioVO objDetBeneVO = new RepDetBeneficiarioVO();
					if (codeSede != null && !codeSede1.equals("nulo")) {
						objDetBeneVO.setCodeSede(new Long((String) codeSede));
					}
					if (codePrograma != null && !codePrograma1.equals("nulo")) {
						objDetBeneVO.setCodePrograma(new Long(
								(String) codePrograma));
					}
					if (codeSubprograma != null
							&& !codeSubprograma1.equals("nulo")) {
						objDetBeneVO.setCodeSubprograma(new Long(
								(String) codeSubprograma));
					}
					if (!fechaini.equals("")) {

						objDetBeneVO.setDesde(fechaini);
					}
					if (!fechafinal.equals("")) {
						objDetBeneVO.setHasta(fechafinal);

					}
					if ((Object) strarea != null && !strarea.equals("nulo")) {
						objDetBeneVO.setCodeArea(new Long(strarea));
					}
					session.setAttribute("Parametros", objDetBeneVO);

					objDetBeneVO = reportTotalBenBerServiceImpl
							.findFilters(objDetBeneVO);
					cobeneficio = reportTotalBenBerServiceImpl
							.findBeneficiosBeneficiarios(objDetBeneVO);

					if (cobeneficio != null) {
						if (cobeneficio.size() > 0) {
							session.setAttribute("Beneficios", cobeneficio);
							session.setAttribute("Filters", objDetBeneVO);
						} else {
							session.removeAttribute("Beneficios");
						}
					}
					objDetBeneVO = null;
				} catch (DAOException e) {
					SUBException.logDebugError("", e);
				}
			}
		}

		Object obIR = request.getParameter("seleccionar");
		if (obIR == null || accion.equals("BuscarSubprogrmas")
				|| accion.equals("areas")) {
			return mapping.findForward("success");
		} else {
			return mapping.findForward("ir");
		}
	}
}